#include <pthread.h>
#include <signal.h>
#include "network.h"

#define MAX_NUMBER 50
#define NAME_LEN 20

typedef struct Client
{
	char name[NAME_LEN];
	pthread_t tid;
	NetWork* nw;
}Client;

NetWork* svrnw;

Client client[MAX_NUMBER];

void send_all(Client* cli,void* buf,size_t len)
{
	for(int i=0; i<MAX_NUMBER; i++)
	{
		if(client[i].tid && client[i].tid != cli->tid)
		{
			nsend(client[i].nw,buf,len);
		}
	}
}

void sigint(int signum)
{
	Client cli = {};
	send_all(&cli,"quit",5);

	for(int i=0; i<MAX_NUMBER; i++)
	{
		if(client[i].tid)
		{
			pthread_cancel(client[i].tid);
			nclose(client[i].nw);
		}
	}

	exit(0);
}


void* run(void* arg)
{
	Client* cli = (Client*)arg;

	char msg[MESSAGE_LEN] = {};
	nrecv(cli->nw,cli->name,sizeof(cli->name));
	
	sprintf(msg,"恭喜 %s 进入房间!!!",cli->name);
	send_all(cli,msg,strlen(msg)+1);

	for(;;)
	{
		char buf[BUFF_LEN] = {};
		if(0 >= nrecv(cli->nw,buf,sizeof(buf)) || !strcmp("quit",buf))
		{
			sprintf(msg,"%s 离开房间!!!",cli->name);
			send_all(cli,msg,strlen(msg)+1);

			cli->tid = 0;
			nclose(cli->nw);
			break;
		}

		sprintf(msg,"%s：%s",cli->name,buf);
		send_all(cli,msg,strlen(msg)+1);
	}
}


int main()
{
	signal(SIGINT,sigint);

	svrnw = nopen(SOCK_STREAM,ADDRESS,PORT,true);

	for(;;)
	{
		NetWork* clinw = naccept(svrnw);
		for(int i=0; i<MAX_NUMBER; i++)
		{
			if(0 == client[i].tid)
			{
				client[i].nw = clinw;
				pthread_create(&client[i].tid,NULL,run,&client[i]);
				break;
			}
		}
	}
}
